﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.Net;

public partial class ForgotPassword : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSendMail_Click(object sender, EventArgs e)
    {
        try
        {
            using (var db = new DiaryOnlineDataContext())
            {
                Diary d = db.Diaries.FirstOrDefault(x => x.Username == txtUsername.Text);
                if (d != null)
                {
                    SendMail(d.Email, d.Username, d.Password);
                }
                else
                {
                    CustomValidator1.ErrorMessage = "Username is not exist";
                    CustomValidator1.IsValid = false;
                }
            }
        }
        catch (Exception ex)
        {
            CustomValidator1.ErrorMessage = ex.Message;
            CustomValidator1.IsValid = false;
        }
    }
    private void SendMail(string email, string username, string password)
    {
        try
        {
            MailAddress from = new MailAddress("support@diaryonline.com");
            MailAddress to = new MailAddress(email);
            MailMessage message = new MailMessage(from, to);
            message.Subject = "Khoi phuc mat khau";
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("Chao {0}, DiaryOnline gui lai mat khau cho ban.\n", username);
            builder.AppendFormat("Mat khau cua ban: {0}", password);
            message.Body = builder.ToString();
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
            smtpClient.Credentials = new NetworkCredential("greytigerbm@gmail.com", "qnt11207");
            smtpClient.Send(message);
            CustomValidator1.IsValid = false;
            CustomValidator1.ErrorMessage = "Send Mail Successfull";
        }
        catch (Exception)
        {
            CustomValidator1.IsValid = false;
            CustomValidator1.ErrorMessage = "Send Mail Fail";
        }
    }
}
